import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Popconfirm, message as componentMessage, Modal} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT, FIXED_COLUMN_WIDTH} from '../constants';
import {addApplyReport} from './api';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import PartClaimReportSelectPanel from './PartClaimReportSelectPanel';
import {partClaimType, currency, partClaimReasonStatus} from '../Enum';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import {injectIntl} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import Return from '../common/Return';
import {newOrUpdateOrderValidator} from './validator';
const FormItem = Form.Item;

class AddPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPartClaimReportSelectPanel: false,
        data: {},
        details: [],
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChangeBrandDetail = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value,
            dealerId: '',
        });
        this.setState({
            hasOperat: true,
            data,
            details: [],
        });
    }
    onChange = (value, name) => {
        const {isDealerUser} = this.props;
        const {details} = this.state;
        if(this.state.data.brandId !== value.id && details.length > 0 && isDealerUser)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'addPanel.message.switch',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'addPanel.message.brandSwitchDetails',
                    defaultMessage: '变更品牌，将会清空索赔结算清单数据，是否清空？'
                }),
                onOk: () => this.onChangeBrandDetail(value, name)
            });
        else if(!isDealerUser && this.state.data.dealerId && this.state.data.brandId !== value.id)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'addPanel.message.switch',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'addPanel.message.isDealerUserSwitchDetails',
                    defaultMessage: '变更品牌，将会清空总代和索赔结算清单数据，是否清空？'
                }),
                onOk: () => this.onChangeBrandDetail(value, name)
            });
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const data = this.state.data;
        const details = this.state.details;
        const {isDealerUser} = this.props;
        const isValid = newOrUpdateOrderValidator(data, details, isDealerUser);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        const condition = {
            brandId: data.brandId,
            dealerId: data.dealerId,
            details: details.map(v => ({
                partClaimReportId: v.partClaimReportId
            }))
        };
        this.setState({loading: true});
        addApplyReport(condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onChangeDealerDetail = record => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                dealerId: record.id,
                dealerCode: record.code,
                dealerName: record.name
            }),
            hasOperat: true,
            details: [],
        });
    }
    onSelectDealer = record => {
        const {details} = this.state;
        if(details.length > 0 && this.state.data.dealerId !== record.id)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'addPanel.message.switch',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'addPanel.message.dealerSwitchDetails',
                    defaultMessage: '变更总代，将会清空索赔结算清单数据，是否清空？'
                }),
                onOk: () => this.onChangeDealerDetail(record)
            });
        this.setState({
            hasOperat: true,
            data: Object.assign({}, this.state.data, {
                dealerId: record.id,
                dealerCode: record.code,
                dealerName: record.name
            })
        });
    }
    onClickAddDetailBtn = () => {
        const {isDealerUser} = this.props;
        if(this.props.initEnumData.brands.length > 1 && !this.state.data.brandId)
            return componentMessage.warning(this.props.intl.formatMessage({
                id: 'addPanel.validate.brandquired',
                defaultMessage: '请先选择品牌'
            }));
        if(!isDealerUser && !this.state.data.dealerId)
            return componentMessage.warning(this.props.intl.formatMessage({
                id: 'addPanel.validate.dealerquired',
                defaultMessage: '请先选择总代'
            }));
        this.setState({
            showPartClaimReportSelectPanel: !this.state.showPartClaimReportSelectPanel
        });
    }
    onSelectPartClaimReports = value => {
        const details = this.state.details;
        value.map(p => {
            const index = this.state.details.findIndex(d => d.id === p.id);
            if(index === -1) {
                const detail = {
                    partClaimReportId: p.reportId,
                    reportCode: p.code,
                    claimCode: p.claimCode,
                    claimType: p.claimType,
                    currency: p.currency,
                    partId: p.partId,
                    partCode: p.partCode,
                    partName: p.partName,
                    packingListCode: p.packingListCode,
                    partSaleOrderCode: p.partSaleOrderCode,
                    cacuQuantity: p.cacuQuantity,
                    price: p.price,
                    mgmtFee: p.mgmtFee,
                    cacuFee: p.cacuFee,
                    claimFee: p.claimFee,
                    claimReason: p.claimReason,
                    id: p.id
                };
                details.push(detail);
            }
            return p;
        });
        this.setState({
            showPartClaimReportSelectPanel: false,
            hasOperat: true,
            details
        });
    }
    onDeleteAll = () => {
        this.setState({
            details: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const id = e.target.dataset.id;
        const details = this.state.details.filter(p => p.id !== id);
        this.setState({
            details,
            hasOperat: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        const {isDealerUser} = this.props;
        if(brands.length === 1)
            data.brandId = brands[0].value;
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName
        } : null;
        let totalFee = 0;
        if(details)
            details.forEach(d => {
                totalFee += (d.cacuFee);
            });
        let claimtTotalFee = 0;
        if(details)
            details.forEach(d => {
                claimtTotalFee += (d.claimFee);
            });
        const columns = [{
            title: formatMessage({
                id: 'addPanel.column.reportCode',
                defaultMessage: '备件索赔报告编号'
            }),
            dataIndex: 'reportCode',
        }, {
            title: formatMessage({
                id: 'addPanel.column.claimType',
                defaultMessage: '索赔类型'
            }),
            dataIndex: 'claimType',
            render: text => conventEnumValueToString(partClaimType, text)
        }, {
            title: formatMessage({
                id: 'addPanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'addPanel.column.claimCode',
                defaultMessage: '备件索赔单编号'
            }),
            dataIndex: 'claimCode',
        }, {
            title: formatMessage({
                id: 'addPanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
        }, {
            title: formatMessage({
                id: 'addPanel.column.partSaleOrderCode',
                defaultMessage: '备件销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'addPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'addPanel.column.partName',
                defaultMessage: '备件中文名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'addPanel.column.cacuQuantity',
                defaultMessage: '结算数量'
            }),
            dataIndex: 'cacuQuantity',
        }, {
            title: formatMessage({
                id: 'addPanel.column.price',
                defaultMessage: '索赔单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'addPanel.column.claimReason',
                defaultMessage: '索赔原因'
            }),
            dataIndex: 'claimReason',
            render: text => conventEnumValueToString(partClaimReasonStatus, text)
        }, {
            title: formatMessage({
                id: 'addPanel.column.claimFee',
                defaultMessage: '赔付金额'
            }),
            dataIndex: 'claimFee',
            render: text => formatAmount(text)
        }, {
            title: details.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'addPanel.validation.isDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'addPanel.validation.clear',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : null,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'addPanel.validation.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        if(!this.props.isDealerUser)
            columns.splice(11, 0, ...[
                {
                    title: formatMessage({
                        id: 'addPanel.column.mgmtFee',
                        defaultMessage: '管理费'
                    }),
                    dataIndex: 'mgmtFee',
                    render: text => formatAmount(text)
                },
            ]);
        if(!this.props.isDealerUser)
            columns.splice(12, 0, ...[
                {
                    title: formatMessage({
                        id: 'addPanel.column.cacuFee',
                        defaultMessage: '结算金额'
                    }),
                    dataIndex: 'cacuFee',
                    render: text => formatAmount(text)
                },
            ]);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'addPanel.column.common',
                        defaultMessage: '备件索赔结算信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item}>
                                        <span className="value-font">{formatMessage({
                                            id: 'addPanel.value.defalut',
                                            defaultMessage: '尚未生成'
                                        })}</span>
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                        <WrappedSelect
                                            name="brandId"
                                            value={data.brandId}
                                            options={brands}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>}
                                { !isDealerUser && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'addPanel.form.dealerId',
                                        defaultMessage: '总代'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.dealerId ? 'error' : null} required>
                                        <DealerSelectPanel
                                            name="dealerId"
                                            value={dealerInfo}
                                            onSelect={this.onSelectDealer} />
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.createTime',
                                        defaultMessage: '申请日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.createTime, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                { !isDealerUser && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.totalFee',
                                        defaultMessage: '结算总金额'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatAmount(totalFee)}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.claimtTotalFee',
                                        defaultMessage: '赔付总金额'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatAmount(claimtTotalFee)}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'addPanel.operation.detail',
                            defaultMessage: '备件索赔结算清单'
                        })} extra={<div>
                            <Button
                                size="small"
                                onClick={this.onClickAddDetailBtn}>
                                {formatMessage({
                                    id: 'addPanel.btn.add',
                                    defaultMessage: '增加清单'
                                })}
                            </Button>
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'addPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                {
                    this.state.showPartClaimReportSelectPanel && <PartClaimReportSelectPanel
                        dealerId={data.dealerId}
                        brandId={data.brandId}
                        selectKey={details.id}
                        onCancel={this.onClickAddDetailBtn}
                        onSelect={this.onSelectPartClaimReports} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

AddPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryCondition,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
    isDealerUser: state.getIn((['page', 'domainData', 'init', 'isDealerUser'])),
    
});
const mapDispatchToProps = (dispatch, props) => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(AddPanel));
